<template>
  <zeda-dialog
    v-model="visible"
    :title="(id <= 0 ? '新增楼层' : '编辑楼层') + ''"
    width="500px"
    :before-close="handleClose"
  >
    <aps-form
      :config="apsForm.formConfig"
      :model="apsForm.formData"
      :formRef="apsForm.formRef"
      :labelWidth="apsForm.labelWidth"
      ref="form"
    ></aps-form>
    <form-button
      slot="footer"
      :loading="loading"
      :submitText="'确定'"
      @cancel="handleClose"
      @submit="submit"
    >
    </form-button>
  </zeda-dialog>
</template>

<script>
import { getfloorDetail, addfloor, editfloor } from "@/api/park/floormsg.js";
import { getparkList } from "@/api/park/parkmsg.js";
import { getbuildingList } from "@/api/park/buildingmsg.js";

import CascaderSelect from "@/components/Select/CascaderSelect";
import FormButton from "@/components/FormButton";
import {
  deepClone,
  replaceDigit,
  replaceInteger,
  dealElectricity,
} from "@/utils/index";

export default {
  dicts: [],
  components: {
    FormButton,
    CascaderSelect,
  },
  props: {
    id: {
      type: [Number, String],
      default: "",
    },
    visible: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      loading: false, // 按钮加载中判断
      parkList: [],
      buildingList: [],
      apsForm: {
        formRef: "form",
        formData: {},
        formConfig: {
          formAttr: {
            // inline: true,
            "label-position": "right",
            size: "small",
            bsColumn: {
              col: 1,
              middle: true,
            },
            rules: {
              parkId: [
                {
                  required: true,
                  message: "请选择园区",
                  trigger: "change",
                },
              ],
              buildingId: [
                {
                  required: true,
                  message: "请选择楼宇",
                  trigger: "change",
                },
              ],
              floorLocation: [
                {
                  required: true,
                  message: "请选择楼层位置",
                  trigger: "change",
                },
              ],
              name: [
                {
                  required: true,
                  message: "请输入楼层名称",
                  trigger: "blur",
                },
                {
                  validator: function (rule, value, callback) {
                    let reg = new RegExp(
                      "^(?!_)(?!.*?_$)[a-zA-Z0-9_\u4e00-\u9fa5]+$"
                    );
                    if (!reg.test(value)) {
                      callback("请勿输入特殊字符，且不能以下划线开头和结尾");
                    } else {
                      callback();
                    }
                  },
                  trigger: "blur",
                },
              ],
              usedArea: [
                {
                  required: false,
                  message: "请输入正确的使用面积",
                  trigger: "blur",
                },
              ],
              publicArea: [
                {
                  required: false,
                  message: "请输入正确的公有面积",
                  trigger: "blur",
                },
              ],
            },
          },
          properties: {
            parkId: {
              label: "园区名称",
              render: (h) => {
                let that = this;
                let arr = [...that.parkList];
                // 数据严谨处理,处理后端数据异常情况
                let valNum = that.$refs?.form?.getFieldsValue().parkId;
                let a = [
                  h(
                    "el-select",
                    {
                      attrs: {
                        placeholder: "请选择园区",
                        value: valNum,
                        clearable: true,
                        disabled: that.disabledFlage,
                      },
                      props: ["value"],
                      on: {
                        change: (value) => {
                          that.$refs?.form?.setFieldValue("parkId", value);
                          that.$forceUpdate();
                        },
                      },
                    },
                    [
                      arr.map((item) => {
                        let { label, value } = item;
                        return h("el-option", {
                          props: {
                            label,
                            value: value,
                            key: value,
                          },
                        });
                      }),
                    ]
                  ),
                ];
                return h("div", a);
              },
            },
            buildingId: {
              label: "楼宇名称",
              render: (h) => {
                let that = this;
                let arr = [...that.buildingList];
                // 数据严谨处理,处理后端数据异常情况
                let valNum = that.$refs?.form?.getFieldsValue().buildingId;
                let a = [
                  h(
                    "el-select",
                    {
                      attrs: {
                        placeholder: "请选择楼宇",
                        value: valNum,
                        clearable: true,
                      },
                      props: ["value"],
                      on: {
                        change: (value) => {
                          that.$refs?.form?.setFieldValue("buildingId", value);
                          that.$forceUpdate();
                        },
                      },
                    },
                    [
                      arr.map((item) => {
                        let { label, value } = item;
                        return h("el-option", {
                          props: {
                            label,
                            value: value,
                            key: value,
                          },
                        });
                      }),
                    ]
                  ),
                ];
                return h("div", a);
              },
            },
            floorLocation: {
              label: "楼层位置",
              typeName: "el-select",
              render: (h) => {
                let that = this;
                let arr = [];
                arr = [
                  {
                    label: "地面",
                    value: 1,
                  },
                  {
                    label: "地下",
                    value: 0,
                  },
                ];
                // 数据严谨处理,处理后端数据异常情况
                let valNum = that.$refs?.form?.getFieldsValue().floorLocation;
                let a = [
                  h(
                    "el-select",
                    {
                      attrs: {
                        placeholder: "请选择楼层位置",
                        value: valNum,
                      },
                      props: ["value"],
                      on: {
                        change: (value) => {
                          that.$refs?.form?.setFieldValue(
                            "floorLocation",
                            value
                          );
                        },
                      },
                    },
                    [
                      arr.map((item) => {
                        let { label, value } = item;
                        return h("el-option", {
                          props: {
                            label,
                            value: value,
                            key: value,
                          },
                        });
                      }),
                    ]
                  ),
                ];
                return h("div", a);
              },
            },
            name: {
              typeName: "el-input",
              label: "楼层名称",
              maxlength: 10,
              placeholder: "请输入楼层名称",
            },
            usedArea: {
              label: "使用面积",
              typeName: "el-input",
              render: (h) => {
                let that = this;
                let a = (
                  <el-input
                    placeholder="请输入使用面积"
                    clearable
                    size="small"
                    maxlength="10"
                    value={that.$refs?.form?.getFieldsValue().usedArea}
                    onInput={(val) => that.replaceDigitDeal(val, 2, "usedArea")}
                  >
                    <template slot="append">
                      <span>㎡</span>
                    </template>
                  </el-input>
                );
                return a;
              },
            },
            publicArea: {
              label: "公有面积",
              typeName: "el-input",
              render: (h) => {
                let that = this;
                let a = (
                  <el-input
                    placeholder="请输入公有面积"
                    clearable
                    size="small"
                    maxlength="10"
                    value={that.$refs?.form?.getFieldsValue().publicArea}
                    onInput={(val) =>
                      that.replaceDigitDeal(val, 2, "publicArea")
                    }
                  >
                    <template slot="append">
                      <span>㎡</span>
                    </template>
                  </el-input>
                );
                return a;
              },
            },
            remarks: {
              label: "备注",
              typeName: "el-input",
              type: "textarea",
              rows: 4,
              maxlength: 200,
              placeholder: "请输入备注",
            },
          },
        },
      },
    };
  },
  watch: {
    visible: {
      handler(value) {
        this.getParklist();
        this.requestBuildinglist();
        if (value) {
          if (String(this.id).length > 0) {
            setTimeout(() => {
              this.getInfo();
            }, 200);
          }
        }
      },
      deep: false,
      immediate: false,
    },
  },
  methods: {
    // 获取园区集合
    getParklist() {
      this.parkList = [];
      getparkList({})
        .then((res) => {
          if (res.code === 700) {
            this.$message.warning(res.msg);
            return false;
          }
          let arr = res?.rows ?? [];
          if (arr.length > 0) {
            arr.map((item) => {
              let obj = {
                label: item?.name ?? "",
                value: item?.id,
              };
              this.parkList.push(obj);
            });
          }
        })
        .catch(() => {
          // this.$message.error("系统错误,请联系管理员!401001");
        });
    },
    // 楼宇集合
    requestBuildinglist() {
      this.buildingList = [];
      getbuildingList({})
        .then((res) => {
          if (res.code === 700) {
            this.$message.warning(res.msg);
            return false;
          }
          let arr = res?.rows ?? [];
          if (arr.length > 0) {
            arr.map((item) => {
              let obj = {
                label: item?.name ?? "",
                value: item?.id,
              };
              this.buildingList.push(obj);
            });
          }
        })
        .catch((err) => {
          // this.$message.error("系统错误,请联系管理员!402001");
        });
    },
    getInfo() {
      getfloorDetail(this.id)
        .then((res) => {
          if (res.code === 700) {
            this.$message.warning(res.msg);
            return false;
          }
          let newData = res?.data || {};
          newData.usedArea = dealElectricity(
            res?.data?.usedArea ?? 0,
            100,
            2,
            "number"
          );
          newData.publicArea = dealElectricity(
            res?.data?.publicArea ?? 0,
            100,
            2,
            "number"
          );
          this.$refs?.form?.setFieldsValue(newData);
        })
        .catch(() => {
          // this.$message.error("系统错误,请联系管理员!403004");
        });
    },
    submit() {
      const data = {
        ...this.$refs.form.getFieldsValue(),
      };
      data.usedArea = Number(data?.usedArea ?? 0) * 100;
      data.publicArea = Number(data?.publicArea ?? 0) * 100;
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.loading = true;
          if (this.id) {
            this.editRequest(data);
          } else {
            this.addRequest(data);
          }
        } else {
          return false;
        }
      });
    },
    addRequest(data) {
      addfloor(data)
        .then((res) => {
          this.loading = false;
          if (res.code === 700) {
            this.$message.warning(res.msg);
            return false;
          }
          this.$message.success("操作成功");
          this.handleClose(true);
        })
        .catch(() => {
          this.loading = false;
          // this.$message.error("系统错误,请联系管理员!403002");
        });
    },
    editRequest(data) {
      editfloor(data)
        .then((res) => {
          this.loading = false;
          if (res.code === 700) {
            this.$message.warning(res.msg);
            return false;
          }
          this.$message.success("操作成功");
          this.handleClose(true);
        })
        .catch(() => {
          this.loading = false;
          // this.$message.error("系统错误,请联系管理员!403003");
        });
    },
    handleClose(status) {
      this.$refs["form"].resetFields();
      this.$emit("update:visible", false);
      this.$emit("close", status === true ? status : false);
    },
    /* 输入限制 */
    // 限制输入保留小数位数
    replaceDigitDeal(val, dit, flage) {
      let result = replaceDigit(val, dit);
      this.$refs?.form?.setFieldValue(flage, result);
    },
    // 限制输入整数
    replaceIntegerDeal(val, flage) {
      let result = replaceInteger(val);
      this.$refs?.form?.setFieldValue(flage, result);
    },
  },
};
</script>

<style scoped lang="scss">
::v-deep .el-form {
  .el-input,
  .el-cascader,
  .el-input-number,
  .el-select {
    width: 100% !important;
  }
  .map {
    display: flex;
    .el-input {
      margin-right: 10px;
    }
  }
}
</style>
